package cn.vire.electric.simulation.config.interceptor;

import cn.vire.electric.simulation.common.dto.Result;
import cn.vire.electric.simulation.config.context.TC;
import cn.vire.electric.simulation.pojo.LoginUserDto;
import cn.vire.electric.simulation.utils.JwtHelper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    public final static String USER_TOKEN_HEAD = "user-token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置返回JSON数据
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;

        boolean isAccess = false;

        String token = request.getHeader(USER_TOKEN_HEAD);
        log.info("当前登录用户[{} = {}]", USER_TOKEN_HEAD, token);
        if (StringUtils.isEmpty(token) && request.getCookies() != null && request.getCookies().length > 0) {
            for (Cookie cookie : request.getCookies()) {
                if (USER_TOKEN_HEAD.equals(cookie.getName())) {
                    token = cookie.getValue();
                    log.info("当前登录用户cookie[{} = {}]", USER_TOKEN_HEAD, token);
                    break;
                }
            }
        }

        if (StringUtils.isEmpty(token)) {
            Result<Object> fail = Result.fail(HttpStatus.FORBIDDEN);
            out = response.getWriter();
            out.append(JSONObject.toJSONString(fail));
            return false;
        }
        try {
            if (JwtHelper.verifyToken(token) != null) {
                //token 不为空的话直接进行校验
                LoginUserDto loginUserDto = JwtHelper.getUserInfo(token);
                log.info("解析用户[{} = {} ]", USER_TOKEN_HEAD, loginUserDto);
                isAccess = true;
                TC.setUserInfo(loginUserDto);
            }
        } catch (Exception e) {
            Result<Object> fail = Result.fail(HttpStatus.UNAUTHORIZED);
            out = response.getWriter();
            out.append(JSONObject.toJSONString(fail));
            return isAccess;
        }

        return isAccess;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        TC.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }


}
